package org.jeecg.modules.doctor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import org.jeecg.common.modules.doctor.entity.DoctorRegister;
import org.jeecg.common.modules.doctor.entity.DoctorRegisterAccount;
import org.jeecg.common.modules.doctor.service.*;
import org.jeecg.common.modules.roomScord.entity.RoomScord;
import org.jeecg.common.modules.roomScord.service.IRoomScordService;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.wx.WeixinUtil;
import org.jeecg.modules.data.service.RegisterService;
import org.springframework.beans.BeanUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.modules.doctor.vo.*;
import org.jeecg.common.modules.patient.service.IPatientService;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.modules.doctor.entity.DoctorRegisterRecord;

import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.data.response.DoctorDeitVo;
import org.jeecg.modules.data.service.DySendMsg;
import org.jeecg.modules.data.service.PageReturn;
import org.jeecg.modules.system.vo.ResultVo;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

import org.jeecg.common.util.enums.RegisterEnum;

/**
 * @Description: doctor_register_record
 * @Author: jeecg-boot
 * @Date: 2020-12-23
 * @Version: V1.0
 */
@Api(tags = "doctor_register_record")
@RestController
@RequestMapping("/doctorRegisterRecord/doctorRegisterRecord")
@Slf4j
public class DoctorRegisterRecordController extends JeecgController<DoctorRegisterRecord, IDoctorRegisterRecordService> {
    @Autowired
    private IDoctorRegisterRecordService doctorRegisterRecordService;
    @Autowired
    private IPatientService patientService;
    @Autowired
    private IDoctorService doctorService;
    @Autowired
    private IDoctorRegisterService doctorRegisterService;
    @Resource
    private IDoctorRegisterHospitalService doctorRegisterHospitalService;
    @Resource
    private IDoctorRegisterAccountService doctorRegisterAccountService;

    @Autowired
    private IRoomScordService roomScordService;
    /**
     * 分页列表查询
     *
     * @param doctorRegisterRecord
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "doctor_register_record-分页列表查询")
    @ApiOperation(value = "doctor_register_record-分页列表查询", notes = "doctor_register_record-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(DoctorRegisterRecord doctorRegisterRecord,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        //分页数据开始的记录数
        int dataStart = (pageNo - 1) * pageSize;

        Integer status = null;
        //（1）先查询所有信息
        String doctorName = req.getParameter("doctorName");
        String patientName = req.getParameter("patientName");
        String statusStr = req.getParameter("status");
        String visitTime = req.getParameter("visitTime");
        if (Objects.nonNull(statusStr)) {
            status = Integer.valueOf(statusStr);
        }

        List<DoctorRegisterRecordSysListVo> recordVos = doctorRegisterRecordService.getRegisterRecordSysList(doctorName, patientName, visitTime, status, dataStart, pageSize);

        //（2）获取总条数
        Integer count = doctorRegisterRecordService.getRegisterRecordSysCount(doctorName, patientName, visitTime , status);

        //（3）组织分页的返回数据
        PageReturn pageReturn = new PageReturn();
        ResultVo vo = pageReturn.initResultVo(recordVos, count, pageNo, pageSize);
        return Result.ok(vo);
    }

    /**
     * 挂号单数据查询
     */
    @GetMapping(value = "/getOne")
    public Result<?> getOne(@RequestParam(name = "recordId") String recordId) {
        DoctorRegisterRecordSysListVo record = doctorRegisterRecordService.getRegisterRecordSysOne(recordId);
        return Result.ok(record);
    }

    /**
     * 挂号单审核操作
     */
    @PostMapping(value = "/examine")
    public Result<?> examine(@RequestBody DoctorRegisterRecordSysListVo requestVo) throws ClientException, ParseException {
        //【一】发送短信
        JSONObject jsonObject = new JSONObject();
        //组织医院科室信息
        String depart = "";
        String departEnd = requestVo.getDepartmentName().substring(requestVo.getDepartmentName().length() - 1);
        if (departEnd.equals("科")) {
            depart = requestVo.getDepartmentName().substring(0, requestVo.getDepartmentName().length() - 1);
        } else {
            depart = requestVo.getDepartmentName();
        }
        log.info("openId\n：{}", requestVo.getOpenid());
        String openid = "";
        String doctorId = "";
        if (Objects.isNull(requestVo.getOpenid())) {
            DoctorRegisterRecordListVo record = doctorRegisterRecordService.getRecordById(requestVo.getId());
            openid = record.getOpenid();
            doctorId = record.getDoctorId();
        }
        //处理日期
        Date visitTime = new SimpleDateFormat("yyyy-MM-dd").parse(requestVo.getVisitTime());
        String visitTimeStr = new SimpleDateFormat("yyyy年MM月dd日").format(visitTime);
        String url = "";
        if (requestVo.getStatus() == RegisterEnum.SUCCESS.getCode()) {  //挂号成功
            jsonObject.put("name_1", requestVo.getPatientName());

            jsonObject.put("hospital_ment", requestVo.getHospitalName() + " " + depart); //xx医院xx科室
            jsonObject.put("name_title", requestVo.getDoctorName() + "(" + requestVo.getTitle() + ")");  //xx医生xx职位
            jsonObject.put("date_part", visitTimeStr + " " + requestVo.getVisitPart());  //xx日期xx时间段
            jsonObject.put("num", requestVo.getVisitNum());  //就诊序号
            jsonObject.put("hospital_2", requestVo.getHospitalAddress());  //医院地址
            jsonObject.put("phone_1", requestVo.getHospitalPhone());   //医院联系电话
            if (CommonUtils.IS_ZS){
                url = "https://zzt.weixin.dyzh120.com/invite-govNew/" ;
            }
            final long l = System.currentTimeMillis();
            final int i = (int)( l % 100000 );
            RoomScord roomScord = new RoomScord();
            roomScord.setDoctorId(requestVo.getId());
            roomScord.setDate(new Date());
            roomScord.setRoomNumber(i);
            roomScord.setDoctorName(requestVo.getDoctorName());
            roomScord.setPatientId(openid);
            roomScord.setPatientName(requestVo.getPatientName());
            roomScord.setStatus("已发送");
            //新增房间记录
            roomScordService.save(roomScord);
            WeixinUtil.pushRegisterSuccess(openid, requestVo.getPatientName(), requestVo.getHospitalName() + " " + requestVo.getDepartmentName(), "预约挂号 " + requestVo.getDoctorName() + "(" + requestVo.getTitle() + ")", visitTimeStr + " " + requestVo.getVisitPart(), requestVo.getHospitalAddress(), "大医智慧", url);
        } else if (requestVo.getStatus() == RegisterEnum.FAIL.getCode()) {  //挂号失败
            jsonObject.put("name", requestVo.getPatientName());
            jsonObject.put("hospital_department", requestVo.getHospitalName() + " " + depart);
            jsonObject.put("doctor", requestVo.getDoctorName());
            jsonObject.put("date_part", visitTimeStr + " " + requestVo.getVisitPart());
            jsonObject.put("phone_2", requestVo.getHospitalPhone());
            if (CommonUtils.IS_ZS){
                url = "https://zzt.weixin.dyzh120.com/invite-govNew/";
            }
            WeixinUtil.pushRegisterFalse(openid, "预约挂号", requestVo.getPatientName(), requestVo.getHospitalName() + " " + requestVo.getDepartmentName(), requestVo.getDoctorName() + "(" + requestVo.getTitle() + ")", visitTimeStr + " " + requestVo.getVisitPart(), "大医智慧", url);
        }

        log.info("短信数据1\n：{}", String.valueOf(jsonObject));
        boolean sendRes = false;
        try {
            if (requestVo.getStatus() == RegisterEnum.SUCCESS.getCode()) {     // 挂号成功
                sendRes = DySendMsg.sendSms(requestVo.getPatientMobile(), jsonObject, DySmsEnum.REGISTER_NOTICE);
            } else if (requestVo.getStatus() == RegisterEnum.FAIL.getCode()) {  // 挂号失败
                sendRes = DySendMsg.sendSms(requestVo.getPatientMobile(), jsonObject, DySmsEnum.REGISTER_FAIL_NOTICE);
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }

        if (sendRes) {
            //【二】更新挂号状态
            DoctorRegisterRecord doctorRegisterRecord = doctorRegisterRecordService.getById(requestVo.getId());
            doctorRegisterRecord.setStatus(requestVo.getStatus());
            doctorRegisterRecord.setExamineTime(new Date());
            doctorRegisterRecord.setFailReason(requestVo.getFailReason());
            boolean recordRes = doctorRegisterRecordService.updateById(doctorRegisterRecord);
            if (!recordRes) {
                return Result.error("处理失败，请稍后重试！");
            }

            return Result.ok("处理成功！");
        } else {
            return Result.error("短信发送失败，请稍后重试！");
        }
    }

    /**
     * 结算信息查询
     */
    @GetMapping(value = "/settle")
    public Result<?> settle(@RequestParam(name = "recordId") String recordId) {
        DoctorRegisterRecordSysSettleVo doctorRegisterRecordSysSettleVo = doctorRegisterRecordService.getRecordSettle(recordId);
        return Result.ok(doctorRegisterRecordSysSettleVo);
    }

    /**
     * 结算数据录入
     */
    @GetMapping(value = "/settleDo")
    public Result<?> settleDo(@RequestParam(name = "recordId") String recordId) {
        DoctorRegisterRecord doctorRegisterRecord = doctorRegisterRecordService.getById(recordId);
        if (Objects.isNull(doctorRegisterRecord)) {
            return Result.error("该挂号信息不存在！");
        } else if (doctorRegisterRecord.getSettle() == 1) {
            return Result.error("改挂号单已结算！");
        }
        DoctorRegister doctorRegister = doctorRegisterService.getById(doctorRegisterRecord.getDoctorRegisterId());
        log.info("挂号信息：{}", doctorRegister);

        DoctorRegisterRecordSysSettleVo doctorRegisterRecordSysSettleVo = doctorRegisterRecordService.getRecordSettle(recordId);
        //【一】添加结算记录
        DoctorRegisterAccount account = new DoctorRegisterAccount();
        account.setDoctorRegisterRecordId(recordId);
        account.setRegisterHospitalId(doctorRegister.getRegisterHospitalId());
        account.setDoctorId(doctorRegister.getDoctorId());
        account.setHospitalAccount(doctorRegisterRecordSysSettleVo.getHospitalProfit());
        account.setDoctorAccount(doctorRegisterRecordSysSettleVo.getDoctorProfit());
        account.setCreateTime(new Date());
        account.setUpdateTime(new Date());
        log.info("结算信息：{}", account);
        boolean accountRes = doctorRegisterAccountService.save(account);

        //【二】更改挂号单结算状态
        doctorRegisterRecord.setSettle(1);
        log.info("挂号单信息：{}", doctorRegisterRecord);
        boolean recordRes = doctorRegisterRecordService.updateById(doctorRegisterRecord);
        if (!recordRes) {
            log.info("挂号结算状态变更失败：{}", recordId);
        }
        if (accountRes) {
            return Result.ok("结算成功！");
        } else {
            return Result.ok("结算失败！");
        }
    }

    /**
     * 添加
     *
     * @param doctorRegisterRecord
     * @return
     */
    @AutoLog(value = "doctor_register_record-添加")
    @ApiOperation(value = "doctor_register_record-添加", notes = "doctor_register_record-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody DoctorRegisterRecord doctorRegisterRecord) {
        doctorRegisterRecordService.save(doctorRegisterRecord);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param doctorRegisterRecord
     * @return
     */
    @AutoLog(value = "doctor_register_record-编辑")
    @ApiOperation(value = "doctor_register_record-编辑", notes = "doctor_register_record-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody DoctorRegisterRecord doctorRegisterRecord) {
        doctorRegisterRecordService.updateById(doctorRegisterRecord);
        return Result.ok("编辑成功!");
    }

    /**
     * 详情
     */
    @GetMapping(value = "/details")
    public Result<?> details(@RequestParam(name = "recordId") String recordId) {

        DoctorRegisterRecord doctorRegisterRecord = doctorRegisterRecordService.getById(recordId);
        if (Objects.isNull(doctorRegisterRecord)) {
            return Result.error("该记录不存在");
        }
        //返回值定义 DoctorRegisterRecordListVo             //服务类 doctorRegisterRecordService   //getRecordById 定义
        DoctorRegisterRecordListVo registerRecord = doctorRegisterRecordService.getRecordById(recordId);  //记录id  recordId
        //定义组合  DoctorResVo       // 重新定义   new DoctorResVo
        DoctorDeitVo recordListResVo = new DoctorDeitVo();


        //进行对象之间的属性赋值  BeanUtils.copyProperties
        BeanUtils.copyProperties(registerRecord, recordListResVo);

        //单独查询设置值（上面没有值到这里查后赋值）
        //压缩后的赋值  doctorRegisterHospitalService.getById(recordListResVo.getRegisterHospitalId()).getName()
        recordListResVo.setRegisterHospitalName(doctorRegisterHospitalService.getById(recordListResVo.getRegisterHospitalId()).getName()); //就诊医院
        recordListResVo.setVisitTime(RegisterService.subStr(recordListResVo.getVisitTime(), 5)); //就诊日期

        //获取医生信息
        DoctorWholeVo doctor = doctorService.doctorWhole(recordListResVo.getDoctorId());

        //多赋值doctor.getName()  doctor.getTitle()  doctor.getDepartmentName()
        recordListResVo.setDoctorName(doctor.getName());
        recordListResVo.setTitle(doctor.getTitle());
        recordListResVo.setDepartmentName(doctor.getDepartmentName());
        recordListResVo.setFailReason(doctorRegisterRecord.getFailReason());
        return Result.ok(recordListResVo);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "doctor_register_record-通过id删除")
    @ApiOperation(value = "doctor_register_record-通过id删除", notes = "doctor_register_record-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        doctorRegisterRecordService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "doctor_register_record-批量删除")
    @ApiOperation(value = "doctor_register_record-批量删除", notes = "doctor_register_record-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.doctorRegisterRecordService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "doctor_register_record-通过id查询")
    @ApiOperation(value = "doctor_register_record-通过id查询", notes = "doctor_register_record-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        DoctorRegisterRecord doctorRegisterRecord = doctorRegisterRecordService.getById(id);
        if (doctorRegisterRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(doctorRegisterRecord);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param doctorRegisterRecord
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DoctorRegisterRecord doctorRegisterRecord) {
        return super.exportXls(request, doctorRegisterRecord, DoctorRegisterRecord.class, "doctor_register_record");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DoctorRegisterRecord.class);
    }
}
